import React, { useState } from 'react';
import { Table, Input, InputNumber, Popconfirm, Form, Typography, message, Button } from 'antd';
import './index.css';
import * as XLSX from 'xlsx';
import { PlusCircleOutlined, FileExcelOutlined } from '@ant-design/icons';
const originData = [];

for (let i = 0; i < 3; i++) {
  originData.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    number: 32,
    price: `${i}`,
  });
}

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `请输入 ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const EditableTable = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [editingKey, setEditingKey] = useState('');
  const [length, setLength] = useState(originData.length);

  const isEditing = record => record.key === editingKey;

  const edit = record => {
    form.setFieldsValue({
      name: '',
      number: '',
      price: '',
      ...record,
    });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async key => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex(item => key === item.key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  const handleDelete = key => {
    const dataSource = data;
    setData(dataSource.filter(item => item.key !== key));
    setLength(length - 1);
    message.success('删除成功!');
  };
  function handleAdd(e) {
    const newData = {
      key: length,
      name: `Edrward ${length}`,
      number: 32,
      price: `${length}`,
    };
    setData([...data, newData]);
    setLength(length + 1);
  }
  const columns = [
    {
      title: '附件名',
      dataIndex: 'name',
      width: '25%',
      editable: true,
    },
    {
      title: '数量',
      dataIndex: 'number',
      width: '15%',
      editable: true,
    },
    {
      title: '单价',
      dataIndex: 'price',
      width: '40%',
      editable: true,
    },
    {
      title: 'operation',
      dataIndex: 'operation',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </Typography.Link>
            <Popconfirm title="确定要取消吗？" onConfirm={cancel} okText="是" cancelText="否">
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <span>
            <Typography.Link
              disabled={editingKey !== ''}
              onClick={() => edit(record)}
              style={{ marginRight: '10px' }}
            >
              编辑
            </Typography.Link>
            <Popconfirm
              title="你确定要删除吗?"
              onConfirm={() => handleDelete(record.key)}
              okText="是"
              cancelText="否"
            >
              <Typography.Link disabled={editingKey !== ''}>删除</Typography.Link>
            </Popconfirm>
          </span>
        );
      },
    },
  ];
  const mergedColumns = columns.map(col => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: record => ({
        record,
        inputType: col.dataIndex === 'name' ? 'text' : 'number',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <>
      <Button
        type="primary"
        size="middle"
        onClick={handleAdd}
        style={{ float: 'left', margin: '10px' }}
      >
        <PlusCircleOutlined />
        添加
      </Button>
      <Button
        type="primary"
        size="middle"
        onClick={readerXlsx}
        style={{ float: 'left', margin: '10px' }}
      >
        <FileExcelOutlined />
        导入Excle
      </Button>
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          bordered
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            onChange: cancel,
          }}
        />
      </Form>
    </>
  );
};
export default EditableTable;
